﻿using DiffuseEnjoyIdle.Core.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace System.Linq
{
    public abstract class ExpressionBuilder
    {
        protected abstract Expression GenExp(Expression left, Expression right);

        /// <summary>
        /// 后缀
        /// </summary>
        public string EndKey { get; protected set; }

        /// <summary>
        /// 表达式类型
        /// </summary>
        public Enum_ConditionType OpType { get; protected set; }

        public Expression BuildExp(ModelExpression.ExpressionItem modelItem, ParamItem paramItem, object param)
        {
            object obj = paramItem.Prop.GetValue(param, null);
            if (this.IsEmpty(obj))
            {
                return null;
            }
            if (obj.GetType() != modelItem.Prop.PropertyType)
            {
                obj = Convert.ChangeType(obj, paramItem.Prop.PropertyType);
            }
            ConstantExpression right = Expression.Constant(obj);
            return this.GenExp(modelItem.Exp, right);
        }

        protected bool AreEquals(object value1, params object[] value2)
        {
            return value2.Any((object x) => x.Equals(value1));
        }

        protected virtual bool IsEmpty(object value)
        {
            if (value == null)
            {
                return true;
            }
            if (this.AreEquals(value, new object[]
            {
                string.Empty,
                -1.7976931348623157E+308,
                -3.4028235E+38f,
                -79228162514264337593543950335m,
                0,
                -2147483648L,
                -2147483648,
                -9223372036854775808L,
                DateTime.MinValue,
                -1.7976931348623157E+308,
                -3.4028235E+38f,
                -79228162514264337593543950335m,
                255,
                2147483647L,
                2147483647,
                9223372036854775807L,
                DateTime.MaxValue
            }))
            {
                return true;
            }
            Type type = value.GetType();
            if (type.IsEnum)
            {
                if (Enum.GetUnderlyingType(type) == typeof(long))
                {
                    if ((long)value == DbSetExt.EmptyEnumValue)
                    {
                        return true;
                    }
                }
                else if ((long)((int)value) == DbSetExt.EmptyEnumValue)
                {
                    return true;
                }
            }
            return false;
        }
    }
}